<template>
  <el-upload
      class="avatar-uploader"
      :action="actionUrl"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :headers="headers"
      :before-upload="beforeUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
    <el-icon v-else class="avatar-uploader-icon">
      <Plus/>
    </el-icon>
  </el-upload>
</template>

<script setup>
import {computed, ref} from 'vue'
import {Plus} from '@element-plus/icons-vue'
import {useUserStore} from "@/store/module/userStore.js";
import {storeToRefs} from "pinia";
import {ElMessage} from "element-plus";
import { deleteFile } from "@/api/file/index.js";

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['upload-success', 'update:modelValue']);
const actionUrl = import.meta.env.VITE_BASE_URL + '/fileUpload';
const {getToken} = storeToRefs(useUserStore());

const imageUrl = computed({
  get: () => props.modelValue,
  set: (data) => {
    emit('update:modelValue', data)
  }
})
const headers = ref({
  token: getToken.value
});
const beforeUpload =async () => {
  if(!imageUrl.value) return;
  let imgUrl = imageUrl.value;
  const prefix = 'zhyl-bucket'
  await deleteFile(imgUrl.substring(imgUrl.lastIndexOf(prefix)+prefix.length));
}
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  const {code, data, msg} = response;
  if (code === 200) {
    ElMessage.success("上传成功！")
    imageUrl.value = data;
  } else {
    ElMessage.error(msg)
  }
}

</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>